package com.vogue.flowmeter.ui.activity;

import android.Manifest;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.maning.mndialoglibrary.MProgressDialog;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.vogue.flowmeter.R;
import com.vogue.flowmeter.api.entity.ApiAuthorizeEntity;
import com.vogue.flowmeter.api.entity.BaseResponse;
import com.vogue.flowmeter.api.event.RecordMessageEvent;
import com.vogue.flowmeter.api.retrofit.NetWorkManager;
import com.vogue.flowmeter.util.DeviceIdUtil;
import com.vogue.flowmeter.util.PrefsUtils;

import org.greenrobot.eventbus.EventBus;

import java.io.IOException;
import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.observers.DefaultObserver;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;

/**
 * 未授权
 */
public class UnauthorizedActivity extends AppCompatActivity {

    private Button btnClose;
    private TextView tvDeviceId;
    private long mPressedTime;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_unauthorized);
        btnClose=findViewById(R.id.btn_close);
        tvDeviceId=findViewById(R.id.tv_device_id);
        btnClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                exitApp(getApplicationContext());
            }
        });
        RxPermissions rxPermissions=new RxPermissions(this);
        rxPermissions.request(Manifest.permission.READ_PHONE_STATE).subscribe(aBoolean -> {
            if (aBoolean){
                String uniqueId= DeviceIdUtil.getDeviceId(this);
                tvDeviceId.setText("设备唯一码："+uniqueId);
            }
        });
    }

    public static void exitApp(Context context){
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.AppTask> appTaskList = activityManager.getAppTasks();
        for (ActivityManager.AppTask appTask : appTaskList) {
            appTask.finishAndRemoveTask();
        }
        android.os.Process.killProcess(android.os.Process.myPid());
        System.exit(0);
    }

    @Override
    public void onBackPressed() {
        //获取第一次按键时间
        long mNowTime = System.currentTimeMillis();
        //比较两次按键时间差
        if ((mNowTime - mPressedTime) > 2000) {
            Toast.makeText(this,"再按一次退出",Toast.LENGTH_LONG).show();
            mPressedTime = mNowTime;
        } else {
            //super.onBackPressed();
            exitApp(getApplicationContext());
        }
    }


    /**
     * 查询授权
     */
    public void onAuthorize(View view) {
        RxPermissions rxPermissions=new RxPermissions(this);
        rxPermissions.request(Manifest.permission.READ_PHONE_STATE).subscribe(aBoolean -> {
            if (aBoolean){
                ApiAuthorizeEntity authorize=new ApiAuthorizeEntity();
                String deviceId= PrefsUtils.getInstance(UnauthorizedActivity.this).get("deviceId","");
                if(TextUtils.isEmpty(deviceId)){
                    return;
                }
                authorize.setDeviceId(deviceId);

                NetWorkManager
                        .getInstance()
                        .getBleApiService()
                        .getAuthorization(authorize)
                        .subscribeOn(Schedulers.io())
                        .doOnSubscribe(disposable -> {
                            MProgressDialog.showProgress(UnauthorizedActivity.this, "加载中...");
                        })
                        .subscribeOn(AndroidSchedulers.mainThread())
                        .subscribe(new DefaultObserver<ResponseBody>() {
                            @Override
                            public void onNext(ResponseBody response) {
                                MProgressDialog.dismissProgress();
                                try {
                                    String body=response.string();
                                    BaseResponse<ApiAuthorizeEntity> res= JSON.parseObject(body,new TypeReference<BaseResponse<ApiAuthorizeEntity>>(ApiAuthorizeEntity.class){});
                                    if (res.getCode()==0&&res.getData()!=null){
                                        if ("authorize_02".equals(res.getData().getStatus())){
                                            PrefsUtils.getInstance(UnauthorizedActivity.this).put("startTime",res.getData().getEmpowerStartTime().getTime());
                                            PrefsUtils.getInstance(UnauthorizedActivity.this).put("endTime",res.getData().getEmpowerEndTime().getTime());
                                            PrefsUtils.getInstance(UnauthorizedActivity.this).put("authorize",res.getData().getStatus());
                                            PrefsUtils.getInstance(UnauthorizedActivity.this).put("phone",res.getData().getPhone()==null? "没有电话号码":res.getData().getPhone());
                                            toMainHandler();
                                        }else {
                                            showToast("权限异常，联系管理员核查("+res.getData().getStatus()+")");
                                        }
                                    }else {
                                        showToast(res.getMsg());
                                    }
                                }catch (IOException i){
                                    showToast(i.getMessage());
                                }
                            }

                            @Override
                            public void onError(Throwable e) {
                                MProgressDialog.dismissProgress();
                                showToast(e.getMessage());
                            }

                            @Override
                            public void onComplete() {
                                MProgressDialog.dismissProgress();
                            }
                        });
                //发送事件出去
                RecordMessageEvent recordMessageEvent = new RecordMessageEvent("onAuthorize", "同步授权");
                EventBus.getDefault().post(recordMessageEvent);
            }
        });

    }

    /**
     * 进入首页
     */
    private void toMainHandler() {
        final Intent intent = new Intent(UnauthorizedActivity.this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
        startActivity(intent);
        finish();
    }
    /**
     *
     * @param msg
     */
    protected void showToast(String msg) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(UnauthorizedActivity.this, msg, Toast.LENGTH_LONG).show();
            }
        });
    }
}